package com.jishuo.nontax.bfc.service;

import com.jishuo.base.bean.BaseResult;
import com.jishuo.base.bean.ErrorCodeEnum;
import com.jishuo.base.config.NonTaxConfig;
import com.jishuo.base.service.SequenceService;
import com.jishuo.nontax.bean.bank.Bank;
import com.jishuo.nontax.bean.bank.BankXml;
import com.jishuo.nontax.bfc.dao.BankMapper;
import com.jishuo.nontax.bfc.tlq.MessageFactory;
import com.jishuo.nontax.bfc.tlq.MessageService;
import org.simpleframework.xml.Serializer;
import org.simpleframework.xml.core.Persister;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.StringWriter;
import java.util.ArrayList;

/**
 * @auther dinggaofei
 * @Date 2022/12/13 13:46
 */
@Service
public class DailiBankService {

    private static Logger logger = LoggerFactory.getLogger(DailiBankService.class);

    @Resource
    private SequenceService sequenceService;
    @Resource
    private MessageService messageService;
    @Resource
    private BankMapper bankMapper;
    @Resource
    private NonTaxConfig nonTaxConfig;

    /**
     * @author hlp
     * @date 2023/2/7 11:27
     * @Description: 获取代理银行信息
     */
    public BaseResult selDailiBank(Long cantonid, String accountcode) {
        try {
            long messageid = sequenceService.getNextSeq("ELEMESSAGESEQ");

            Bank bank = MessageFactory.getBank(cantonid, accountcode);
            //xml解析器
            Serializer serializer = new Persister();
            //xml转换器
            StringWriter sw = new StringWriter();
            String  bankcls =  nonTaxConfig.Sender;
            BankXml xml = new BankXml();
            //发送到财政
            boolean suc = messageService.sendAndRecvMessage("GETBANK", messageid, bank, "2.3");
            if (suc) {
                ArrayList<Bank> list = bankMapper.selBank(bankcls,cantonid, accountcode);
                //查询返回记录
                if (list != null && list.size() > 0) {
                    xml.setBank(list);
                    serializer.write(xml, sw);
                    return new BaseResult(sw.toString());
                }
            }
            return new BaseResult("<bills></bills>");
        } catch (Exception e) {
            logger.info(" 处理代理银行信息失败：" + e.toString());
            return new BaseResult(ErrorCodeEnum.UNKNOWN_ERR, "<bills></bills>");
        }
    }



    public BaseResult getDailiBank(Long cantonid,String accountcode){
        try {
            long messageid = sequenceService.getNextSeq("ELEMESSAGESEQ");
            Object dailiBankDTO = MessageFactory.getDailiBankDTO(cantonid, accountcode, nonTaxConfig.Sender);
            //发送到财政
            messageService.sendMessage("GETBANK", messageid,dailiBankDTO, "2.3");
            return new BaseResult();
        } catch (Exception e) {
            logger.info(" 处理代理银行信息失败："+e.toString());
            return new BaseResult(ErrorCodeEnum.UNKNOWN_ERR);
        }
    }

}

